package com.breadenglish.cms.api.app.sys.manager;

import com.breadenglish.cms.api.app.domain.constants.Constants;
import com.breadenglish.cms.api.app.domain.model.ResultMessage;
import com.breadenglish.cms.api.app.sys.context.MessageContextHolder;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;

/**
 * 异常处理跳转控制
 * User: guoyao
 * Date: 13-12-24
 * Time: 下午3:51
 */
@Controller
@RequestMapping("/sys")
public class ExceptionController {

    private Logger logger = LoggerFactory.getLogger(ExceptionController.class);

    /**
     * 返回类型为ModelAndView的异常处理控制
     *
     * @param message 异常消息体
     * @return
     */
    @RequestMapping(value = "/forwardModelAndView.html")
    public ModelAndView forwardModelAndView(@Param("message") ResultMessage message) {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("error");
        mav.addObject(Constants.ERROR_MESSAGE_NAME, message);
        return mav;
    }

    @RequestMapping(value = "/forwardResponseBody.html")
    @ResponseBody
    public ResultMessage forwardResponseBody(HttpServletResponse response) {
        // 获取异常信息对象上下文
        ResultMessage message = MessageContextHolder.getResultMessage();
        MessageContextHolder.removeResultMessage();
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        return message;
    }

    @RequestMapping(value = "/forwardResponseEntity.html")
    public ResponseEntity<ResultMessage> forwardResponseEntity() {
        HttpHeaders responseHeaders = new HttpHeaders();
        MediaType mediaType = new MediaType("text", "json", Charset.forName("UTF-8"));
        responseHeaders.setContentType(mediaType);
        // 获取异常信息对象上下文
        ResultMessage message = MessageContextHolder.getResultMessage();
        MessageContextHolder.removeResultMessage();
        return new ResponseEntity<ResultMessage>(message, responseHeaders, HttpStatus.INTERNAL_SERVER_ERROR);
    }

}
